<template>
  <div class="config-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>系统参数配置</span>
          <el-button type="primary" :icon="Check" @click="handleSave" :loading="saveLoading">保存更改</el-button>
        </div>
      </template>

      <el-form v-if="!loading" ref="formRef" :model="configForm" label-position="top">
        <el-tabs v-model="activeTab">
          <el-tab-pane v-for="(group, groupName) in groupedConfigs" :key="groupName" :label="groupName" :name="groupName">
            <div class="form-group">
              <el-form-item v-for="config in group" :key="config.configKey" :label="config.configName">
                <el-input v-model="config.configValue" placeholder="请输入配置值" style="max-width: 400px; margin-right: 20px"/>
                <div class="remark-text">{{ config.remark }}</div>
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div v-else v-loading="loading" style="height: 200px;"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Check } from '@element-plus/icons-vue';
import { getConfigList, updateConfigs } from '@/api/modules/config';
import { useConfigStore } from '@/store/modules/config';

const loading = ref(true);
const saveLoading = ref(false);
const formRef = ref(null);
const allConfigs = ref([]); // 存储从API获取的原始列表
const activeTab = ref('提醒'); // 默认激活的页签
const configStore = useConfigStore();

const configForm = computed(() => {
  return allConfigs.value;
});

// 将配置按 group 分组
const groupedConfigs = computed(() => {
  return allConfigs.value.reduce((acc, config) => {
    const group = config.configGroup || 'Default';
    if (!acc[group]) {
      acc[group] = [];
    }
    acc[group].push(config);
    return acc;
  }, {});
});


const fetchData = async () => {
  loading.value = true;
  try {
    allConfigs.value = await getConfigList();
  } catch (error) {
    console.error("获取配置列表失败", error);
  } finally {
    loading.value = false;
  }
};

const handleSave = async () => {
  saveLoading.value = true;
  try {
    await updateConfigs(configForm.value);
    // 更新成功后，通知Pinia Store也刷新一下缓存
    await configStore.fetchConfigs();
    ElMessage.success('配置已成功保存！');
  } catch (error) {
    console.error("保存配置失败", error);
  } finally {
    saveLoading.value = false;
  }
};

onMounted(fetchData);
</script>

<style scoped>
.config-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-group {
  padding: 20px;
}
.remark-text {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 5px;
}
</style>
